package util

import (
	"crypto/rand"
	"fmt"
	"path/filepath"
	"strings"
	"time"
)

// IsValidImageType 验证是否为支持的图片类型
func IsValidImageType(contentType string) bool {
	allowedTypes := []string{
		"image/jpeg",
		"image/jpg",
		"image/png",
		"image/gif",
		"image/webp",
	}

	for _, allowedType := range allowedTypes {
		if contentType == allowedType {
			return true
		}
	}
	return false
}

// IsValidImageExtension 验证图片文件扩展名
func IsValidImageExtension(filename string) bool {
	ext := strings.ToLower(filepath.Ext(filename))
	allowedExts := []string{".jpg", ".jpeg", ".png", ".gif", ".webp"}

	for _, allowedExt := range allowedExts {
		if ext == allowedExt {
			return true
		}
	}
	return false
}

// GenerateUniqueFilename 生成唯一文件名
// 格式：时间戳_随机字符串.扩展名
func GenerateUniqueFilename(originalFilename string) (string, error) {
	ext := filepath.Ext(originalFilename)

	// 生成随机字符串
	randomBytes := make([]byte, 16)
	_, err := rand.Read(randomBytes)
	if err != nil {
		return "", err
	}

	// 生成时间戳
	timestamp := time.Now().Unix()

	// 组合文件名
	filename := fmt.Sprintf("%d_%x%s", timestamp, randomBytes, ext)

	return filename, nil
}

// GenerateRandomString 生成指定长度的随机字符串
func GenerateRandomString(length int) string {
	const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	b := make([]byte, length)
	rand.Read(b)
	for i := range b {
		b[i] = charset[b[i]%byte(len(charset))]
	}
	return string(b)
}

// GetImageExtensionFromContentType 根据Content-Type获取文件扩展名
func GetImageExtensionFromContentType(contentType string) string {
	switch contentType {
	case "image/jpeg":
		return ".jpg"
	case "image/png":
		return ".png"
	case "image/gif":
		return ".gif"
	case "image/webp":
		return ".webp"
	default:
		return ".jpg" // 默认
	}
}
